package jsyf.oa.dao.wechat.service_account;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.oa.entity.system.CompanyEntity;
import jsyf.oa.entity.wechat.service_account.WeChatUserEntity;
import jsyf.oa.idao.BaseDao;
import jsyf.oa.ientity.IBaseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class WeChatUserDao extends BaseDao {

    public WeChatUserDao() {
        super.iBaseEntity = new WeChatUserEntity();
    }
    @Override
    public IBaseEntity convertJson2Entity(JSONObject json) {
        return JSON.toJavaObject(json, WeChatUserEntity.class);
    }

    public Boolean isExitByOpenId(String openId) {
        String sql = "select count(1) from T_WECHAT_SERVICE_USER WHERE OPEN_ID = ?";
        return (Integer.valueOf(super.queryForString(sql, new Object[]{openId}))) > 0;
    }

    public Boolean isExitByCustomerTel(String customerTel) {
        String sql = "select count(1) from T_WECHAT_SERVICE_USER WHERE CUSTOMER_TEL = ? AND SUBSCRIBE = 1";
        return (Integer.valueOf(super.queryForString(sql, new Object[]{customerTel}))) > 0;
    }

    public int updateByOpenId(String openId, int status) {

        String sql = "UPDATE T_WECHAT_SERVICE_USER SET SUBSCRIBE = ? WHERE OPEN_ID = ?";
        JdbcTemplate jdbcTemplate = super.getJdbcTemplate();
        int rows = jdbcTemplate.update(sql, new Object[]{status, openId});
        return rows;
    }

    public int updateByCustomerTel(String openId, String phone) {

        String sql = "UPDATE T_WECHAT_SERVICE_USER SET CUSTOMER_TEL = ? WHERE OPEN_ID = ?";
        JdbcTemplate jdbcTemplate = super.getJdbcTemplate();
        int rows = jdbcTemplate.update(sql, new Object[]{phone, openId});
        return rows;
    }

    public int updateByEventKey(String openId, String eventKey) {

        JSONObject jsonObject = (JSONObject) JSONObject.parse(eventKey);
        String customerTel = jsonObject.getString("customerTel");
        String salerId = jsonObject.getString("salerId");

        String sql = "UPDATE T_WECHAT_SERVICE_USER SET CUSTOMER_TEL = ? , SALER_ID = ? WHERE OPEN_ID = ?";
        JdbcTemplate jdbcTemplate = super.getJdbcTemplate();
        int rows = jdbcTemplate.update(sql, new Object[]{customerTel, salerId, openId});
        return rows;
    }
}